﻿using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Admin.IService;
using Admin.Model;
using Admin.Model.RequestModel;
using Microsoft.AspNetCore.Mvc;

namespace Admin.Web.Controllers.Api
{
    public class SysRoleController : ApiController
    {
        private ISysRoleService _sysRoleService;
        private ISysUserRoleService _sysUserRoleService;
        public SysRoleController(ISysRoleService sysRoleService, ISysUserRoleService sysUserRoleService)
        {
            _sysRoleService = sysRoleService;
            _sysUserRoleService = sysUserRoleService;
        }

        #region 查询接口
        /// <summary>
        /// 
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <param name="cName"></param>
        /// <param name="eName"></param>
        /// <param name="status"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<InfoModel> QueryRolePage(int page = 0, int pageSize = 10, string cName = null, string eName = null, int? status = null, string startTime = null, string endTime = null)
        {
            #region 查询条件
            string sqlWhere = "";
            if (cName != null)
            {
                sqlWhere = $"{sqlWhere}and CName like concat('%', @cName, '%')";
            }
            if (eName != null)
            {
                sqlWhere = $"{sqlWhere}and EName  like concat('%', @eName, '%') ";
            }
            if (status != null)
            {
                sqlWhere = $"{sqlWhere}and Status=@status ";
            }
            if (startTime != null)
            {
                sqlWhere = $"{sqlWhere}and date_format(CreateTime,'%y%m%d') >= date_format(@startTime,'%y%m%d')";
            }
            if (endTime != null)
            {
                sqlWhere = $"{sqlWhere}and date_format(CreateTime,'%y%m%d') <= date_format(@endTime,'%y%m%d')";
            }
            #endregion

            var rows = await _sysRoleService.GetPage(page, pageSize, new { cName, eName, status, startTime, endTime }, sqlWhere);
            int total = await _sysRoleService.GetCount(new { cName, eName, status, startTime, endTime }, sqlWhere);
            return DataReturn(new { total, rows }, "添加");
        }

        /// <summary>
        /// 角色中文名称检测
        /// </summary>
        /// <param name="cName"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<bool> CheckRoleCName(string CName, string Id = "") => await _sysRoleService.IsExist(new { CName, Id }, $"CName=@CName{(Id != "" ? " and Id != @Id" : "")}");
        /// <summary>
        /// 角色英文名称检测
        /// </summary>
        /// <param name="cName"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<bool> CheckRoleEName(string EName, string Id = "") => await _sysRoleService.IsExist(new { EName, Id }, $"EName=@EName{(Id != "" ? " and Id != @Id" : "")}");

        #endregion

        #region 操作接口
        /// <summary>
        /// 角色新增
        /// </summary>
        /// <param name="requestRole"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<InfoModel> AddSave([FromBody]RequestRole requestRole)
        {
            #region 数据封装
            requestRole.CreateTime = DateTime.Now;
            requestRole.CreateBy = HttpContext.User.Claims.Where(o => o.Type == ClaimTypes.NameIdentifier).FirstOrDefault().Value;
            #endregion

            int res = await _sysRoleService.AddSave(requestRole);

            return OpReturn(res, "添加");
        }
        /// <summary>
        /// 角色修改
        /// </summary>
        /// <param name="requestRole"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<InfoModel> EditSave([FromBody]RequestRole requestRole)
        {
            #region 数据封装
            requestRole.UpdateTime = DateTime.Now;
            requestRole.UpdateBy = HttpContext.User.Claims.Where(o => o.Type == ClaimTypes.NameIdentifier).FirstOrDefault().Value;
            #endregion

            int res = await _sysRoleService.EditSave(requestRole);

            return OpReturn(res, "修改");
        }
        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<InfoModel> Delete([FromBody]RequestDelete ids)
        {
            string sqlWhere = "";
            foreach (string str in ids.ids.Split(","))
            {
                sqlWhere = $"{sqlWhere}{int.Parse(str)},";
            }
            //判断角色是否使用中
            var user = await _sysUserRoleService.GetList(null, $"RoleId in ({sqlWhere.TrimEnd(',')})", "");
            if (user.Count() > 0)
                return OpReturn(0, "", "角色正在使用中无法删除");
            int res = await _sysRoleService.Delete(int.Parse(ids.ids));
            return OpReturn(res, "删除");
        }

        /// <summary>
        /// 取消授权
        /// </summary>
        /// <param name="sysUserRole"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<InfoModel> CancelAuthUser([FromBody]SysUserRole sysUserRole)
        {
            int res = await _sysUserRoleService.Delete(sysUserRole, "UserId=@UserId and RoleId=@RoleId");
            return OpReturn(res, "取消授权");
        }

        /// <summary>
        /// 批量取消授权
        /// </summary>
        /// <param name="cancelAuthUser"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<InfoModel> CancelAuthUserAll([FromBody]AuthUser cancelAuthUser)
        {
            int res = await _sysUserRoleService.CancelAuthUser(cancelAuthUser);
            return OpReturn(res, "取消授权");
        }
        /// <summary>
        /// 授权
        /// </summary>
        /// <param name="authUser"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<InfoModel> AuthUser([FromBody]AuthUser authUser)
        {
            int res = await _sysUserRoleService.AuthUser(authUser);
            return OpReturn(res, "授权");
        }
        #endregion
    }
}